package cn.com.openportal.ffw.common.aspect;

import cn.com.openportal.ffw.common.exception.RRException;
import cn.com.openportal.ffw.common.utils.Constant;
import cn.com.openportal.ffw.common.utils.SQLFilterUtils;
import cn.com.openportal.ffw.common.utils.ShiroUtils;
import cn.com.openportal.ffw.modules.sys.entity.SysUserEntity;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 数据过滤，切面处理类
 *
 * @author LeeSon
 */
@Aspect
@Component
public class DataFilterAspect {
    private static Logger logger = LoggerFactory.getLogger(DataFilterAspect.class);

    @Autowired
    private SQLFilterUtils SQLFilterUtils;

    @Pointcut("@annotation(cn.com.openportal.ffw.common.annotation.DataFilter)")
    public void dataFilterCut() {
    }

    @Before("dataFilterCut()")
    public void dataFilter(JoinPoint point) {
        try {
            Object params = point.getArgs()[0];
            if (params != null && params instanceof Map) {
                SysUserEntity user = ShiroUtils.getUserEntity();

                //如果不是超级管理员，则进行数据过滤
                if (user.getUserId() != Constant.SUPER_ADMIN) {
                    Map map = (Map) params;
                    map.put(Constant.SQL_FILTER, SQLFilterUtils.getSQLFilter(user, point));
                }

                return;
            }
            logger.error("数据权限接口参数错误 "+params.getClass().getName());
            throw new RRException("数据权限接口参数错误");
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            throw new RRException("发生错误，请联系管理员");
        }
    }
}
